package com.vgooo.util;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.LocalActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.vgooo.client.Constants;

public class Utils {
	public static Map<String, Object> getMap(String jsonString) {
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(jsonString);
			Iterator<String> keyIter = jsonObject.keys();
			String key;
			Object value;
			Map<String, Object> valueMap = new HashMap<String, Object>();
			while (keyIter.hasNext()) {
				key = (String) keyIter.next();
				value = jsonObject.get(key);
				valueMap.put(key, (Object) value);
			}
			return valueMap;
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static ArrayList<Map<String, Object>> getArrayList(String jsonString)
			throws JSONException {
		JSONArray json = new JSONArray(jsonString);

		ArrayList<Map<String, Object>> arraylist = new ArrayList<Map<String, Object>>();
		JSONObject jsonObject;

		for (int i = 0; i < json.length(); i++) {
			jsonObject = json.getJSONObject(i);
			arraylist.add(Utils.getMap(jsonObject.toString()));
		}
		return arraylist;
	}

	// 下载图片
	public static Bitmap downloadBitmap(String url) {
		InputStream stream = null;
		BufferedInputStream bis = null;
		URL imageUrl;
		Bitmap bmp = null;
		HttpURLConnection conn = null;

		try {
			imageUrl = new URL(url);
			conn = (HttpURLConnection)imageUrl.openConnection();
			conn.setDoInput(true);
			conn.connect();
			if (conn.getContentLength() > 300 * 1024) {
				Utils.saveTxt(url);
				return null;
			}
			stream = conn.getInputStream();
			bis = new BufferedInputStream(stream);
			bmp = BitmapFactory.decodeStream(bis);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (stream != null) {
					stream.close();
				}
				if (bis != null) {
					bis.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}

		return bmp;
	}

	// 获取URL的文件名称
	public static String getFileName(String url, boolean ext) {
		String fileName = null;

		String[] fields = url.split("/");
		fileName = fields[fields.length - 1];

		if (!ext) {
			String[] exts = fileName.split("\\.");

			fileName = "";
			for (int i = 0; i < exts.length; i++) {
				if (i + 1 == exts.length) {
					break;
				}
				fileName += exts[i];
				if (i + 2 < exts.length) {
					fileName += ".";
				}
			}
		}

		return fileName;
	}

	// SDCard操作
	public static final String SDCARD_PATH = "/sdcard/vgooo";

	// 判断文件是否存在
	public static boolean fileExist(String fileName) {
		return fileExist(fileName, 0);
	}

	// 判断文件是否存在以为符合大小
	public static boolean fileExist(String fileName, Object size) {
		String sizeString = String.valueOf(size);

		int size1 = 0;
		try {
			if (sizeString.indexOf(".") > -1 && sizeString != null) {
				size1 = Integer.parseInt(sizeString.substring(0,
						sizeString.indexOf(".")));
			} else if (sizeString != "") {
				size1 = Integer.parseInt(sizeString);
			}
		} catch (Exception e) {
			return false;
		}
		String sDStateString = android.os.Environment.getExternalStorageState();

		if (sDStateString.endsWith(android.os.Environment.MEDIA_MOUNTED)) {

			File destDir = new File(SDCARD_PATH);
			if (!destDir.exists()) {
				destDir.mkdirs();
			}

			File file = new File(SDCARD_PATH + File.separator + fileName);
			if (file.exists()) {
				if (size1 == 0) {
					return false;
				} else if (file.length() == size1) {
					return true;
				}
			}
		}
		return false;
	}

	// 从SDCARD读取
	public static String SDCardRead(String fileName) {
		String sDStateString = android.os.Environment.getExternalStorageState();

		if (sDStateString.endsWith(android.os.Environment.MEDIA_MOUNTED)) {

			File destDir = new File(SDCARD_PATH);
			if (!destDir.exists()) {
				destDir.mkdirs();
			}

			File imageFile = new File(SDCARD_PATH + File.separator + fileName);
			if (imageFile.exists()) {
				return SDCARD_PATH + File.separator + fileName;
			}
		}

		return null;
	}

	// 从SDCARD写入
	public static void SDCardWrite(Bitmap bmp, String fileName) {
		String sDStateString = android.os.Environment.getExternalStorageState();

		if (sDStateString.endsWith(android.os.Environment.MEDIA_MOUNTED)) {
			// 检测存储卡空间
			File sdcardDir=Environment.getExternalStorageDirectory();
			StatFs statFs=new StatFs(sdcardDir.getPath());
			/** Block 的 size*/
			Long blockSize=(long) statFs.getBlockSize();
			Long availableBlocks=(long) statFs.getAvailableBlocks();

			// 小于1M退出
			if (availableBlocks * blockSize < 1024 * 1024 ) return;
			
			File destDir = new File(SDCARD_PATH);
			if (!destDir.exists()) {
				destDir.mkdirs();
			}
			File file = new File(SDCARD_PATH + File.separator + fileName);
			if (!file.exists()) {
				CompressFormat format = Bitmap.CompressFormat.PNG;
				int quality = 100;
				OutputStream stream = null;
				try {
					stream = new FileOutputStream(file);

					bmp.compress(format, quality, stream);
				} catch (Exception e) {
					
				} finally {
					try {
						stream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}

	public static String countsize(Object size) {
		if (size.toString().indexOf("M") > -1) {
			return size.toString();
		}

		Double size2 = Double.valueOf(String.valueOf(size));
		String size3 = String.valueOf(size2 / 1024 / 1024);
		if (size3.indexOf(".") > 0 && size3.length() - size3.indexOf(".") > 3) {
			size3 = size3.substring(0, size3.indexOf(".") + 3);
		}
		return size3 + " M";
	}

	public static String stampToDate(String cc_time) {
		String re_StrTime = null;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		long lcc_time = Long.valueOf(cc_time);
		re_StrTime = sdf.format(new Date(lcc_time * 1000L));

		return re_StrTime;
	}

	public static boolean isWifi(Context mContext) {
		ConnectivityManager connectivityManager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		if (activeNetInfo != null
				&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
			return true;
		}
		return false;
	}

	/**
	 * 判断是否有网络连接
	 * 
	 * @param mContext
	 * @return boolean
	 * */
	public static boolean hasNetWork(Context mContext) {
		boolean netSataus = false;
		ConnectivityManager cwjManager = (ConnectivityManager) mContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cwjManager.getActiveNetworkInfo() != null) {
			netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
		}

		return netSataus;
	}
	
	/**
	 * 网络异常提示
	 * @param context
	 * @param content
	 * @return
	 */
	public static boolean netWorkInfoToast(Context context){
		if(hasNetWork(context)){
			return false ;
		}else{
			Toast.makeText(context, "未联网，请检查网络设置！", Toast.LENGTH_LONG).show();
			return true ;
		}
	}

	// SD卡是否可用
	public static boolean isSDCardAvable() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	// 加1
	public static void downPlugsCount(final String app_id) {

		new Thread(new Runnable() {

			@Override
			public void run() {
				RequestService rs = new RequestService(MyUrl.APP_FILE_GET, null);
				rs.addParam("app_id", app_id);
				try {
					rs.doPost();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();

	}

	// 保存文本数据
	public static void saveTxt(final String string) {

		new Thread(new Runnable() {

			@Override
			public void run() {
				RequestService rs = new RequestService(MyUrl.SAVE_TXT_URL, null);
				rs.addParam("txt", string);
				try {
					rs.doPost();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();

	}
	
	// 检测内存是否过低
	public static boolean isLowMemory(Context context) {
        if (null == context) {
            return false;
        }

        ActivityManager am = (ActivityManager)
                        context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(outInfo);

        return outInfo.lowMemory;
    }
	
	
	/**
	 * get the external storage file
	 * 
	 * @return the file
	 */
	public static File getExternalStorageDir() {
		return Environment.getExternalStorageDirectory();
	}

	/**
	 * get the external storage file path
	 * 
	 * @return the file path
	 */
	public static String getExternalStoragePath() {
		return getExternalStorageDir().getAbsolutePath();
	}

	/**
	 * get the external storage state
	 * 
	 * @return
	 */
	public static String getExternalStorageState() {
		return Environment.getExternalStorageState();
	}

	/**
	 * check the usability of the external storage.
	 * 
	 * @return enable -> true, disable->false
	 */
	public static boolean isExternalStorageEnable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;

	}

	

	// public static final void hideSoftInputFromWindow(EditText editText,
	// Context context){
	// InputMethodManager imm = (InputMethodManager)
	// context.getSystemService(Context.INPUT_METHOD_SERVICE);
	// imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	// }

	/**
	 * judge the list is null or isempty
	 * 
	 * @param list
	 * @return
	 */
	public static boolean isEmpty(final List<? extends Object> list) {
		if (list == null || list.isEmpty()) {
			return true;
		}
		return false;
	}

	public static boolean isEmpty(final Set<? extends Object> sets) {
		if (sets == null || sets.isEmpty()) {
			return true;
		}
		return false;
	}
	public static boolean isEmpty(final Map<? extends Object,? extends Object> map) {
		if (map == null || map.isEmpty()) {
			return true;
		}
		return false;
	}

	/**
	 * Returns true if the string is null or 0-length.
	 * 
	 * @param text
	 * @return
	 */
	public static boolean isEmpty(final String text) {
		return TextUtils.isEmpty(text);
	}

	/**
	 * return true ,if the string is numeric
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumeric(final String str) {
		if (isEmpty(str)) {
			return false;
		}
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	/**
	 * get the width of the device screen
	 * 
	 * @param context
	 * @return
	 */
	public static int getSceenWidth(Context context) {
		return context.getResources().getDisplayMetrics().widthPixels;
	}

	/**
	 * get the height of the device screen
	 * 
	 * @param context
	 * @return
	 */
	public static int getSceenHeight(Context context) {
		return context.getResources().getDisplayMetrics().heightPixels;
	}

	/**
	 * 
	 * @param context
	 * @return
	 */
	public static float getSceenDensity(Context context) {
		return context.getResources().getDisplayMetrics().density;
	}

	/**
	 * convert the dip value to px value
	 * 
	 * @param context
	 * @param dipValue
	 * @return
	 */
	public static float dip2px(Activity context, float dps) {
		 DisplayMetrics metrics = new DisplayMetrics(); 
         float density = metrics.density;
         context.getWindowManager().getDefaultDisplay().getMetrics(metrics);
         density = metrics.density;
         float pixels = dps * density;
         return pixels;
	}

	/**
	 * convert the string to another string which is build by the char value
	 * 
	 * @param str
	 * @return
	 */
	public static String toCharString(String str) {
		if (TextUtils.isEmpty(str)) {
			str = "null";
		}
		String strBuf = "";
		for (int i = 0; i < str.length(); i++) {
			int a = str.charAt(i);
			strBuf += Integer.toHexString(a).toUpperCase();
		}
//		strBuf=String.valueOf(str.hashCode());
		return strBuf;
	}

	/**
	 * hide the input method
	 * 
	 * @param view
	 */
	public static void hideSoftInput(View view) {
		if (view == null)
			return;
		InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		if (imm.isActive()) {
			imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0);
			if(view instanceof EditText){
				view.clearFocus();
				view.focusSearch(View.FOCUS_UP);
			}
		}
	}

	/**
	 * show the input method
	 * 
	 * @param view
	 */
	public static void showSoftInput(View view) {
		if (view == null)
			return;
		view.requestFocus();
		InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(view, 0);
	}
	public static void initExternalDir(boolean cleanFile)
	{
		if(Utils.isExternalStorageEnable())
		{
			File external = new File(Constants.EXTERNAL_DIR);
			if(!external.exists())
			{
				external.mkdirs();
			}
			//check the cache whether exist
			File cache = new File(Constants.CACHE_DIR);
			if(!cache.exists())
			{
				cache.mkdirs();
			}
			else
			{
				if(cleanFile)
				{
					//if exist,so clear the old file
					cleanFile(cache, TimeUtils.WEEK_MILLIS);
				}
			}
			//check the log dir
			File logs = new File(Constants.LOGS_DIR);
			if(!logs.exists())
			{
				logs.mkdirs();
			}
			else
			{
				if(cleanFile)
				{
					cleanFile(logs, TimeUtils.HALF_MONTH_MILLIS);
				}
			}
			
			File files = new File(Constants.FILES_DIR);
			if(!files.exists())
			{
				files.mkdirs();
			}
			else
			{
				if(cleanFile)
				{
					cleanFile(logs, 0);
				}
			}
			
			File data = new File(Constants.DATA_DIR);
			if(!data.exists())
			{
				data.mkdirs();
			}
		}
	}
	public static int cleanFile(File dir, long maxInterval)
	{
		File[] files = dir.listFiles();
		if(files == null) return 0;
		int beforeNum = 0;
		long current = System.currentTimeMillis();
		for(File file:files)
		{
			long lastModifiedTime = file.lastModified();
			if((current-lastModifiedTime) > maxInterval)
			{
				//if the file is exist more than a week , so need to delete.
				file.delete();
				beforeNum ++;
			}
		}
		return beforeNum;
	}
	
	/**
	 * 弹出土司
	 * @param activity 
	 * @param content 土司显示的内容
	 */
    protected static void showToast(final Activity activity,final String content) {
        activity.runOnUiThread(new Runnable() {
            
            @Override
            public void run() {
                Toast toast = Toast.makeText(activity, content, Toast.LENGTH_SHORT);
                toast.show();
                
            }
        });
       
    }
    
    /**
     * 设置文本框显示的内容
     * @param activity  
     * @param textView 文本框
     * @param content  显示的内容
     */
    protected static void setTextViewContent(final Activity activity,final TextView textView,final String content) {
        activity.runOnUiThread(new Runnable() {
            
            @Override
            public void run() {
               if(textView!=null){
                   textView.setText(content);
               }
                
            }
        });
       
    }
    
    
    
    public static String getIMEI(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getDeviceId();
	}

	public static String getIMSI(Context context) {
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		return tm.getSubscriberId();	
	}
	

	/**
	 * 将秒转化成00:00的格式字符串
	 * 
	 * @param seconds
	 * @return
	 */
	public static String secondsToString(int seconds) {
		String s = "" + seconds / 60 + ":";
		int t = seconds % 60;
		s += t < 10 ? "0" + t : t;
		return s;
	}

	/**
	 * 将字节数转换成MB
	 */
	public static String byteToMB(int bt) {
		DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
		df.setMaximumFractionDigits(2);
		return df.format(bt / (1024.0 * 1024)) + " MB";
	}

	/**
	 * 将字节数转换成KB
	 */
	public static String byteToKB(int bt) {
		DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
		df.setMaximumFractionDigits(2);
		return df.format(bt / 1024.0) + " KB";
	}

	/**
	 * 速度转化（...kb/s,...mb/s,...b/s）
	 */
	public static String speedTransform(float speed) {
		DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
		df.setMaximumFractionDigits(2);

		if (speed < 1024) {
			return df.format(speed) + " b/s";
		}
		if (speed >= 1024 && speed < 1024 * 1024) {
			return df.format(speed / 1024) + " kb/s";
		}
		if (speed >= 1024 * 1024) {
			return df.format(speed / (1024 * 1024)) + " mb/s";
		}
		return "";
	}

	public static String getLocalIpAddress() {
		try {
			for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en
					.hasMoreElements();) {
				NetworkInterface intf = (NetworkInterface) en.nextElement();
				for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr
						.hasMoreElements();) {

					InetAddress inetAddress = (InetAddress) enumIpAddr
							.nextElement();
					if (!inetAddress.isLoopbackAddress()) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
		}
		return "";
	}

	/**
	 * 获取包的版本号
	 */
	public static String getVersionName(Context context) {
		try {
			PackageInfo packageInfo = context.getPackageManager()
					.getPackageInfo("com.dj.act", 0);
			return packageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "nuknow";
		}
	}

	/**
	 * 获得android版本
	 */
	public static int getAndroidSDKVersion() {
		int version = 0;
		try {
			version = Integer.valueOf(android.os.Build.VERSION.SDK);
			//			System.out.println(version);
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return version;
	}

	/**
	 * 获取缩略图
	 * 
	 * @return
	 */
	public static Bitmap getThumbnailBitmap(String absPath, float aimWidth,
			float aimHeight) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true; // 获取这个图片的宽和高

		File mFile = new File(absPath);
		if (!mFile.exists()) {
			return null;
		}
		BitmapFactory.decodeFile(absPath, options); // 此时返回 bm 为 空		

		/*int issW = (int) (options.outWidth / aimWidth);
		int issH = (int) (options.outHeight / aimHeight);

		int iss = (int) ((issW + issH) / 2 + mFile.length() / (1024 * 1024 * 3));
		iss = Math.max(1, iss);

		options.inSampleSize = iss; // 重新读入图片，注意这次要把
		*/
		
		/**
		 * Modified by LiYongNam 2012.11.26_start
		 */		
		int wRatio = (int) Math.ceil(options.outWidth / aimWidth );
		int hRatio = (int) Math.ceil(options.outHeight / aimHeight);
		if (wRatio > 1 && hRatio > 1) {
			if (wRatio > hRatio) {
				options.inSampleSize = wRatio;
			} else {
				options.inSampleSize = hRatio;
			}
		}		
		/**
		 * Modified by LiYongNam 2012.11.26_end
		 */		
		
		
		options.inJustDecodeBounds = false;

		Bitmap bitmap = BitmapFactory.decodeFile(absPath, options);

		return bitmap;
	}

	/**
	 * 图片圆角
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int roundPx) {

		if (bitmap == null) {
			return null;
		}

		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);
		// final float roundPx = 400;

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		// bitmap.recycle();
		bitmap = null;

		return output;
	}

	/**
	 * dip 转 PX
	 */
	public static int dipTopx(Context context, float dipValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	/**
	 * 从系统的缩略图数据库中，获取图片Id
	 * 
	 * @param file
	 * @param cr
	 * @return
	 */
	public static long getImageID(File file, ContentResolver cr) {
		long result = -1;

		Cursor c = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				new String[] {
					BaseColumns._ID + ""
				}, MediaColumns.DATA + "=?", new String[] {
					file.getAbsolutePath()
				}, null);

		c.moveToNext();

		if (!c.isAfterLast()) {
			result = c.getLong(0);
		}

		c.close();

		return result;
	}

	/**
	 * 
	 */
	public static int getDisplayWidth(Activity act) {
		return act.getWindowManager().getDefaultDisplay().getWidth();
	}

	public static int getDisplayHeight(Activity act) {
		return act.getWindowManager().getDefaultDisplay().getHeight();
	}

	public static int getMinWidth(Activity act) {
		return Math.min(getDisplayWidth(act), getDisplayHeight(act));
	}

	/**
	 * 通过context获得宽度、高度
	 */
	public static int getWidthPixels(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getResources().getDisplayMetrics();

		return dm.widthPixels;
	}

	public static int getHeightPixels(Context context) {
		DisplayMetrics dm = new DisplayMetrics();
		dm = context.getResources().getDisplayMetrics();

		return dm.heightPixels;
	}

	/*
	 * 根据路径生成等比例图片
	 */
	public static Bitmap decodeBitmap(String path, int displayWidth,
			int displayHeight) {
		BitmapFactory.Options op = new BitmapFactory.Options();
		op.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(path, op);
		int wRatio = (int) Math.ceil(op.outWidth / (float) displayWidth);
		int hRatio = (int) Math.ceil(op.outHeight / (float) displayHeight);
		if (wRatio > 1 && hRatio > 1) {
			if (wRatio > hRatio) {
				op.inSampleSize = wRatio;
			} else {
				op.inSampleSize = hRatio;
			}
		}		
		
		op.inJustDecodeBounds = false;
		Bitmap bitmap = BitmapFactory.decodeFile(path, op);
		if (bitmap == null) {
			return null;
		}
		return Bitmap.createScaledBitmap(bitmap, displayWidth, displayHeight,
				true);
	}

//	public static Bitmap cropBitmap(String path, int displayWidth,
//			int displayHeight) {
//		// Part 1: Decode image
//		Bitmap unscaledBitmap = ScalingUtilities.decodePath(path, displayWidth,
//				displayHeight, ScalingLogic.CROP);
//		if (unscaledBitmap == null) {
//			return null;
//		}
//		// Part 2: Scale image
//		Bitmap scaledBitmap = ScalingUtilities.createScaledBitmap(
//				unscaledBitmap, displayWidth, displayHeight, ScalingLogic.CROP);
//		unscaledBitmap.recycle();
//
//		return scaledBitmap;
//	}
	
	/**
	 * Added by LiYongNam 2012.9.30_start	 
	 */

//	public static Bitmap decodeBitmapFromRes(int resId, int displayWidth,
//			int displayHeight) {
//		BitmapFactory.Options op = new BitmapFactory.Options();
//		op.inJustDecodeBounds = true;
//		BitmapFactory.decodeResource(MusicApplication.getInstance().getResources(), resId, op);		
//		int wRatio = (int) Math.ceil(op.outWidth / (float) displayWidth);
//		int hRatio = (int) Math.ceil(op.outHeight / (float) displayHeight);
//		if (wRatio > 1 && hRatio > 1) {
//			if (wRatio > hRatio) {
//				op.inSampleSize = wRatio;
//			} else {
//				op.inSampleSize = hRatio;
//			}
//		}
//		op.inJustDecodeBounds = false;
//		Bitmap bitmap = BitmapFactory.decodeResource(MusicApplication.getInstance().getResources(), resId, op);
//		if (bitmap == null) {
//			return null;
//		}
//		return Bitmap.createScaledBitmap(bitmap, displayWidth, displayHeight,
//				true);
//	}
	/**
	 * Added by LiYongNam 2012.9.30_end	 
	 */
	
	public static int dBToProgress( short volume ){
		short VOLUME_MAX = 1500;
		short VOLUME_MIN = -1500;
		
		if ( volume > VOLUME_MAX ) {
			volume = VOLUME_MAX;			
		}
		else if ( volume < VOLUME_MIN ){
			volume = VOLUME_MIN;
		}
		
		return ( int ) ( ( volume - VOLUME_MIN ) * 100 / (VOLUME_MAX - VOLUME_MIN ) );
	}
	
	public static short progressTodB ( int progress ){
		short VOLUME_MAX = 1500;
		short VOLUME_MIN = -1500;
		return ( short ) ( ( progress - 50 ) * ( VOLUME_MAX - VOLUME_MIN) / 100 );
	}
	/**
	 * Added by LiYongNam 2012.11.16_start
	 */
	/**
	 * Added by LiYongNam 2012.11.16_end
	 */

	public static String getThumbImageIdByPath(Activity act, String path) {
		ContentResolver cr = act.getContentResolver();
		String[] pro = {
				MediaStore.Images.Thumbnails.DATA,
				MediaStore.Images.Thumbnails.IMAGE_ID
		};
		Cursor c = cr.query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
				pro,
				MediaStore.Images.Thumbnails.DATA + "=" + "'" + path + "'",
				null, null);
		String str;
		if (c.moveToFirst()) {
			str = c.getString(c
					.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
			c.close();
		} else {
			c.close();
			return null;
		}
		return str;
	}

	public static void Assert(boolean cond) {
		if (!cond) {
			throw new AssertionError();
		}
	}

	/**
	 * Activity转换成View
	 * 
	 * @param parent
	 * @param target
	 * @param state
	 * @return
	 */
	public static View activityToView(Activity parent, Class<?> target,
			Bundle state) {

		LocalActivityManager mLocalActivityManager = new LocalActivityManager(
				parent, true);// new一个本地的activity管理器
		mLocalActivityManager.dispatchCreate(state);// 这个state就是当前Activity的状态参数，就是onCreate(Bundle
													// savedInstanceState)里面这个savedInstanceState
		mLocalActivityManager.dispatchResume();
		mLocalActivityManager.dispatchDestroy(true);

		Intent intent = new Intent(parent, target);

		final Window w = mLocalActivityManager.startActivity(target.getName(),
				intent);// 取得一个window对象，以方便转换为View
		final View wd = w != null ? w.getDecorView() : null;// 转换为view
		if (wd != null) {
			wd.setVisibility(View.VISIBLE);
			wd.setClickable(true);
			wd.setFocusable(true);
			wd.setFocusableInTouchMode(true);
			((ViewGroup) wd)
					.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
		}
		return wd;
	}

	/**
	 * 获取屏幕的亮度 0 -- 255
	 */
	public static int getScreenBrightness(ContentResolver contentResolver) {
		int nowBrightnessValue = 0;
		try {
			nowBrightnessValue = android.provider.Settings.System.getInt(
					contentResolver, Settings.System.SCREEN_BRIGHTNESS);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return nowBrightnessValue;
	}

	/**
	 * 设置亮度
	 */
	public static void setBrightness(Activity activity, int brightness) {
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.screenBrightness = Float.valueOf(brightness) * (1f / 255f);
		activity.getWindow().setAttributes(lp);

	}

//	public static void createShortCut(final Activity mAct, boolean isCreat) {
//
//		SharedPreferences shareData = mAct.getSharedPreferences("dj", 0);
//		String isExtraShowName = shareData.getString("EXTRA_SHORTCUT_NAME", "");
//		if (isExtraShowName.equals("NEW")) {
//			if (isCreat) {
//				Intent intent = new Intent(
//						"com.android.launcher.action.INSTALL_SHORTCUT");// action
//				intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
//						mAct.getString(R.string.app_name));// 快捷方式名字
//				intent.putExtra("duplicate", false); // 是否重复创建快捷方式
//				Parcelable icon = Intent.ShortcutIconResource.fromContext(mAct,
//						R.drawable.ic_launcher);
//				intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);// icon
//				intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(mAct,
//						MainActivity.class)); // 启动界面
//				mAct.sendBroadcast(intent);// 发送广播
//			}
//		} else {
//			final EnterWindow mWindow = new EnterWindow(mAct);
//			mWindow.addTitle("创建快捷方式");
//			mWindow.addTextView("是否创建桌面快捷方式?");
//			mWindow.addEnterButton(new String[] {
//					"创建", "取消"
//			}, new EnterClickListener() {
//
//				@Override
//				public void onClick(ArrayList<String> editText,
//						ArrayList<Boolean> isCheck,
//						ArrayList<Integer> radioGroup, int tag) {
//					// TODO Auto-generated method stub
//					mWindow.dismiss();
//					if (tag == 0) {
//						Intent intent = new Intent(
//								"com.android.launcher.action.INSTALL_SHORTCUT");// action
//						intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
//								mAct.getString(R.string.app_name));// 快捷方式名字
//						intent.putExtra("duplicate", false); // 是否重复创建快捷方式
//						Parcelable icon = Intent.ShortcutIconResource
//								.fromContext(mAct, R.drawable.ic_launcher);
//						intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
//								icon);// icon
//						intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
//								new Intent(mAct, MainActivity.class)); // 启动界面
//						mAct.sendBroadcast(intent);// 发送广播
//					}
//					SharedPreferences shareData = mAct.getSharedPreferences(
//							"dj", 0);
//					Editor editor = shareData.edit();
//					editor.putString("EXTRA_SHORTCUT_NAME", "NEW");
//					editor.commit();
//				}
//			});
//			mWindow.show();
//		}
//
//	}
	
	/** 
	 * 判断当前网络是否为 wifi 
	 * @param mContext 
	 * @return 
	 */  
//	public static boolean isWifi() {  
//		Context mContext = MusicApplication.getInstance();
//	    ConnectivityManager connectivityManager = (ConnectivityManager) mContext  
//	            .getSystemService(Context.CONNECTIVITY_SERVICE);  
//	    NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();  
//	    if (activeNetInfo != null  
//	            && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {  
//	        return true;  
//	    }  
//	    return false;  
//	}  
//	
//	public static boolean isPlayInWifi(){
//		if(MusicApplication.getInstance().getSetupConfig().isOnlyUseWifi()){
//			if(isWifi()){
//				return false ;
//			}else{
//				MusicApplication.getInstance().toast.setText("仅在wifi下在线播放！");
//				MusicApplication.getInstance().toast.show();
//				return true ;
//			}
//		}else{
//			return false ;
//		}
//	}
	

}
